package com.helloworld.view;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.helloworld.R;
import com.helloworld.utils.RecorderUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class ReadRawsActivity extends AppCompatActivity {

    private String TAG=this.getClass().getSimpleName();
    Button mBtn;
    private MediaPlayer mediaPlayer;
    private SoundPool soundPool;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_read_raws);
        RecorderUtil.recordingPermissions(this);
        mBtn= (Button) findViewById(R.id.btn_read_raw);
//         mediaPlayer =  MediaPlayer.create(ReadRawsActivity.this,R.raw.perfect);
//        try {
//            mediaPlayer.prepareAsync();
//        } catch (IllegalStateException e){
//            e.printStackTrace();
//        }
        mBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                rawPlay();
//                playAsset();
//                soundPoolPlay();
            }
        });


    }

    private void soundPoolPlay() {
        soundPool=new SoundPool(5, AudioManager.STREAM_MUSIC,0);
        soundPool.load(this,R.raw.verygood,1);
        soundPool.play(1,1, 1, 0, 0, 1);
    }

    private void playAsset() {
        try {
            AssetManager assetManager = this.getAssets();
            AssetFileDescriptor afd = assetManager.openFd("good.mp3");
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setDataSource(afd.getFileDescriptor(),
                    afd.getStartOffset(), afd.getLength());

            mediaPlayer.setLooping(true);//循环播放
            mediaPlayer.prepareAsync();
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mp.start();
                }
            });
//            mediaPlayer.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void rawPlay() {
//        String playUrl="http://jiayin-10076642.video.myqcloud.com/jsmy02/Wfdcd07c6-fd1e-43f0-afa0-1cda7b0c5df4.mp3";
        String playUrl = "android.resource://" + getPackageName() + "/" + R.raw.test;
        if (mediaPlayer!=null&&mediaPlayer.isPlaying()){
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer=null;
        }else {
            try {
//            mediaPlayer.reset();
                mediaPlayer =new MediaPlayer();
                mediaPlayer.setDataSource(ReadRawsActivity.this, Uri.parse(playUrl));
                mediaPlayer.setLooping(true);//循环播放
                mediaPlayer.prepareAsync();
//                mediaPlayer.start();
//            mediaPlayer.start();

                mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mp) {
                        Log.d(TAG,"onPrepared");
                        mediaPlayer.start();
                        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                            @Override
                            public void onCompletion(MediaPlayer mp) {
                                Log.d(TAG," setOnPreparedListener complete");
//                    stopPlay();
                            }
                        });
                    }
                });
                mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        Log.d(TAG,"complete");
                        mediaPlayer.stop();
                        mediaPlayer.release();
                        mediaPlayer=null;
                    }
                });
//            new Handler(){
//                @Override
//                public void handleMessage(Message msg) {
//                    super.handleMessage(msg);
//                    stopPlay();
//                }
//            }.sendEmptyMessageDelayed(0,1000);

            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    String inputStream2String(InputStream is) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(is));
        StringBuffer buffer = new StringBuffer();
        String line = "";
        while ((line = in.readLine()) != null){
            buffer.append(line);
        }
        return buffer.toString();
    }
    private MediaPlayer getMediaPlayer(Context context) {
        MediaPlayer mediaplayer = new MediaPlayer();
        if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT) {
            return mediaplayer;
        }
        try {
            Class<?> cMediaTimeProvider = Class.forName("android.media.MediaTimeProvider");
            Class<?> cSubtitleController = Class.forName("android.media.SubtitleController");
            Class<?> iSubtitleControllerAnchor = Class.forName("android.media.SubtitleController$Anchor");
            Class<?> iSubtitleControllerListener = Class.forName("android.media.SubtitleController$Listener");
            Constructor constructor = cSubtitleController.getConstructor(
                    new Class[]{Context.class, cMediaTimeProvider, iSubtitleControllerListener});
            Object subtitleInstance = constructor.newInstance(context, null, null);
            Field f = cSubtitleController.getDeclaredField("mHandler");
            f.setAccessible(true);
            try {
                f.set(subtitleInstance, new Handler());
            } catch (IllegalAccessException e) {
                return mediaplayer;
            } finally {
                f.setAccessible(false);
            }
            Method setsubtitleanchor = mediaplayer.getClass().getMethod("setSubtitleAnchor",
                    cSubtitleController, iSubtitleControllerAnchor);
            setsubtitleanchor.invoke(mediaplayer, subtitleInstance, null);
        } catch (Exception e) {
            Log.d(TAG,"getMediaPlayer crash ,exception = "+e);
        }
        return mediaplayer;
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopPlay();
    }

    private void stopPlay() {
        if (mediaPlayer!=null){
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer=null;
        }
    }
}
